<template>
    <div class="image-uploader">
        <div class="upload-section">
            <ImageUpload 
                v-model="fileList"
                label="上传图片"
                placeholder="点击上传图片"
                :multiple="true"
                :maxCount="500"
                :maxSize="1024 * 1024 * 1024"
                @error="handleError"
            />
        </div>

        <!-- 图库列表 -->
        <div class="gallery-list">
            <div class="list-header">
                <h3>图库列表</h3>
                <div class="header-actions">
                    <div class="page-size-control">
                        <Field
                            v-model="pageSizeInput"
                            placeholder="输入每页显示数量"
                            type="number"
                            @blur="handlePageSizeInput"
                        />
                        <div class="quick-options">
                            <span 
                                v-for="size in [5, 10, 20, 50]" 
                                :key="size"
                                :class="{ active: pageSize === size }"
                                @click="setPageSize(size)"
                            >
                                {{ size }}条/页
                            </span>
                        </div>
                    </div>
                    <van-button size="small" type="primary" @click="refreshGallery">刷新</van-button>
                    <van-button size="small" type="primary" @click="selectAll">全选</van-button>
                    <van-button size="small" type="primary" plain @click="unselectAll">取消全选</van-button>
                    <van-button size="small" type="danger" @click="clearFiles">清空</van-button>
                </div>
            </div>
            <div class="list-content">
                <div v-if="loading" class="loading-state">
                    <van-loading type="spinner" size="24" />
                    <span>加载中...</span>
                </div>
                <div v-else-if="error" class="error-state">
                    <van-icon name="warning-o" size="24" />
                    <span>{{ errorMessage }}</span>
                    <van-button size="small" @click="refreshGallery">重试</van-button>
                </div>
                <div v-else-if="galleryList.length === 0" class="empty-state">
                    <van-icon name="photo-o" size="24" />
                    <span>暂无图片</span>
                </div>
                <table v-else class="gallery-table">
                    <thead>
                        <tr>
                            <th class="th-serial">

                                <van-checkbox 
                                        v-model="isAllSelected"
                                        @change="handleSelectAll"
                                    />
                            </th>
                                
                            <th class="th-serial">序号</th>
                            <th class="th-preview">预览</th>
                            <th class="th-info">文件信息</th>
                            <th class="th-actions">操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(image, index) in galleryList" :key="image.id || index" class="gallery-row">
                            <td class="td-checkbox">
                                <van-checkbox 
                                    v-model="selectedItems[index]" 
                                    @change="updateSelection"
                                />
                            </td>
                            <td class="td-serial">{{ getSerialNumber(index) }}</td>
                            <td class="td-preview">
                                <div class="image-preview-cell">
                                    <img :src="image.url" :alt="image.fileName" @click="previewImage(image)" />
                                </div>
                            </td>
                            <td class="td-info">
                                <div class="file-name" :title="truncateFileName(image.fileName) || '未知文件'">{{ truncateFileName(image.fileName)   || '未知文件' }}</div>
                                <div class="file-meta">
                                    <span class="file-size">{{ image.fileSize }}MB</span>
                                    <span class="upload-time">{{ formatTime(image.createdAt) }}</span>
                                </div>
                                <div class="mobile-file-size">
                                    <van-icon name="description" class="size-icon" />
                                    {{ image.fileSize }}MB
                                </div>
                            </td>
                            <td class="td-actions">
                                <div class="time-display">
                                    <div class="time-info">
                                        <van-icon name="clock-o" class="time-icon" />
                                        {{ formatTime(image.createdAt) }}
                                    </div>
                                </div>
                                <van-icon name="delete" @click="deleteImage(image)" class="action-icon" />
                            </td>
                        </tr>
                    </tbody>
                </table>
                <div v-if="total > pageSize" class="pagination-wrapper">
                    
                    <Pagination
                        :current-page="currentPage" 
                        :total-pages="totalPages" 
                        :total="total"
                        @page-change="goToPage" 
                    />
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, computed, watch, nextTick } from 'vue';
import { 
    Icon as VanIcon, 
    Button as VanButton,
    Loading as VanLoading,
    Checkbox as VanCheckbox,
    Field,
    Popup,
    showToast,
    showImagePreview,
    showDialog
} from 'vant';
import ImageUpload from '@/Pages/compontents/ImageUpload.vue';
import Pagination from '@/Pages/compontents/Pagination.vue';
import apiUrls from '@/config/apiUrls';
import request from '@/utils/request';
import { truncateFileName } from '@/utils/utils';

const fileList = ref([]);
const galleryList = ref([]);
const loading = ref(false);
const error = ref(false);
const errorMessage = ref('');
const currentPage = ref(1);
const pageSize = ref(20);
const isAllSelected = ref(false);
const total = ref(0)

const totalPages = computed(() => {
    return Math.ceil(total.value / pageSize.value);
});

// 监听每页显示数量变化
watch(pageSize, () => {
    currentPage.value = 1;
});

// 跳转到指定页
const goToPage = async (page) => {
    if (page < 1 || page > totalPages.value) return;
    currentPage.value = page;
    await fetchGalleryList();
};

// 获取图库列表
const fetchGalleryList = async () => {
    loading.value = true;
    error.value = false;
    errorMessage.value = '';

    try {
        const response = await request.get(apiUrls.imageManger.imageMager, {
            params: {
                currentPage: currentPage.value,
                pageSize: pageSize.value
            }
        });

        if (response.code === 200) {
            galleryList.value = response.data.list || [];
            total.value = response.data.total || 0;
        } else {
            error.value = true;
            errorMessage.value = response.message || '获取图库列表失败';
        }
    } catch (err) {
        error.value = true;
        errorMessage.value = '获取图库列表失败，请重试';
        console.error('获取图库列表失败:', err);
    } finally {
        loading.value = false;
        // 恢复滚动位置
      
    }
};

// 刷新图库
const refreshGallery = () => {
     // 保存当前滚动位置
     const scrollPosition = document.documentElement.scrollTop || document.body.scrollTop;
    fetchGalleryList().then(()=>{
        nextTick(() => {
            window.scrollTo(0, scrollPosition);
        });
    });
};


// 处理全选框变化
const handleSelectAll = (checked) => {
    // 更新所有选择框的状态
    galleryList.value.forEach((_, index) => {
        selectedItems.value[index] = checked;
    });
    isAllSelected.value = checked;
    updateSelection();
};

// 删除图片
const deleteImage = async (image) => {
    try {
        // 显示确认对话框
        await showDialog({
            title: '确认删除',
            message: '是否确认删除选中的图片？',
            showCancelButton: true,
        });
        
        await request.delete(apiUrls.imageManger.imageMager, {
            data: { ids:  [image.id]}
        });
        // 更新列表
        await fetchGalleryList();
        showToast('删除成功');
        
    } catch (err) {
        showToast(err.message || '删除失败');
    }
};



// 预览图片
const previewImage = (image) => {
    showImagePreview({
        images: [image.url],
        startPosition: 0,
        closeable: true,
        closeIconPosition: 'top-right',
    });
};


// 格式化时间
const formatTime = (time) => {
    if (!time) return '';
    const date = new Date(time);
    return date.toLocaleString();
};

// 获取选中的图片
const getSelectedImages = () => {
    return galleryList.value.filter((_, index) => selectedItems.value[index]);
};

// 判断是否有选中的项目
const hasSelectedItems = computed(() => {
    return Object.values(selectedItems.value).some(value => value);
});

// 清空选中的文件
const clearFiles = async () => {
    if (!hasSelectedItems.value) {
        showToast('请先选择要删除的图片');
        return;
    }

    try {
        // 显示确认对话框
        await showDialog({
            title: '确认删除',
            message: '是否确认删除选中的图片？',
            showCancelButton: true,
        });

        const selectedImages = getSelectedImages();
        
        // 执行删除操作
        const imageIds = selectedImages.map(image => image.id);
        await request.delete(apiUrls.imageManger.imageMager, {
            data: { ids: imageIds }
        });

        // 更新列表
        await fetchGalleryList();
        showToast('删除成功');
        
        // 重置选择状态
        selectedItems.value = {};
    } catch (err) {
        if (err.message !== 'cancel') { // 忽略取消操作的错误
            showToast(err.message || '删除失败');
        }
    }
};

// 处理上传错误
const handleError = (error) => {
    showToast(error.message || '上传失败，请重试');
};


// 添加序列号计算方法
const getSerialNumber = (index) => {
    return (currentPage.value - 1) * pageSize.value + index + 1;
};

// 选中项管理
const selectedItems = ref({});

// 全选功能
const selectAll = () => {
    galleryList.value.forEach((_, index) => {
        selectedItems.value[index] = true;
    });
    updateSelection();
};

// 取消全选
const unselectAll = () => {
    galleryList.value.forEach((_, index) => {
        selectedItems.value[index] = false;
    });
    updateSelection();
};

// 更新选择状态
const updateSelection = () => {
    // 获取选中的项目
    const selectedImages = galleryList.value.filter((_, index) => selectedItems.value[index]);
};

// 监听页面变化时重置选择状态
watch(currentPage, () => {
    selectedItems.value = {};
});

// 处理每页显示数量变化
const handlePageSizeChange = () => {
    currentPage.value = 1; // 重置到第一页
    fetchGalleryList(); // 重新获取列表
};

const pageSizeInput = ref('20');

// 处理手动输入
const handlePageSizeInput = () => {
    const value = parseInt(pageSizeInput.value);
    if (value && value > 0) {
        pageSize.value = value;
        currentPage.value = 1;
        fetchGalleryList();
    } else {
        pageSizeInput.value = pageSize.value;
        showToast('请输入有效的数字');
    }
};

// 设置页面大小
const setPageSize = (size) => {
    const scrollPosition = document.documentElement.scrollTop || document.body.scrollTop;
    pageSize.value = size;
    pageSizeInput.value = size;
    currentPage.value = 1;
    fetchGalleryList().then(()=>{
        nextTick(() => {
            window.scrollTo(0, scrollPosition);
        });
    });
};

onMounted(() => {
    fetchGalleryList();
});
</script>

<style scoped>
.image-uploader {
    padding: 20px;
}

.upload-section {
    background: #f8f9fa;
    padding: 20px;
    border-radius: 8px;
    border: 2px dashed #ddd;
}

.gallery-list {
    margin-top: 20px;
    background: #fff;
    border-radius: 8px;
    padding: 16px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
}

.header-actions {
    display: flex;
    gap: 8px;
    align-items: center;
}

.list-header h3 {
    margin: 0;
    font-size: 16px;
    color: #333;
}

.gallery-item {
    display: flex;
    align-items: center;
    padding: 12px;
    border-bottom: 1px solid #f5f5f5;
    gap: 12px;
}

.gallery-item:last-child {
    border-bottom: none;
}

.serial-number {
    width: 24px;
    text-align: center;
    color: #666;
    font-size: 14px;
}

.image-preview {
    width: 60px;
    height: 60px;
    flex-shrink: 0;
    border-radius: 4px;
    overflow: hidden;
    background: #f8f9fa;
}

.image-preview img {
    width: 100%;
    height: 100%;
    object-fit: contain;
}

.image-info {
    flex: 1;
    min-width: 0;
}

.file-name {
    font-size: 14px;
    color: #333;
    margin-bottom: 4px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.file-size {
    font-size: 12px;
    color: #999;
    margin-bottom: 4px;
}

.upload-time {
    font-size: 12px;
    color: #999;
}

.image-actions {
    padding: 0 12px;
    color: #999;
    cursor: pointer;
    transition: color 0.3s;
}

.image-actions:hover {
    color: #ee0a24;
}

.loading-state,
.error-state,
.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px;
    color: #666;
    gap: 8px;
}

.pagination-wrapper {
    margin-top: 16px;
    padding-top: 16px;
    border-top: 1px solid #f5f5f5;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 16px;
}

.pagination-info {
    color: #606266;
    font-size: 13px;
}

.gallery-table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 10px;
}

.gallery-table th,
.gallery-table td {
    padding: 12px 10px;
    border-bottom: 1px solid #f0f2f5;
    vertical-align: middle;
    font-size: 13px;
}

.gallery-table th {
    background-color: #fafafa;
    font-weight: 600;
    color: #606266;
    text-align: left;
}

.th-serial, .td-serial {
    width: 50px;
    text-align: center;
}

/* 特别定义第一列的宽度和对齐方式 */
.gallery-table th:first-child,
.gallery-table .td-checkbox {
    width: 40px;
    padding: 0;
    height: 100px;
    text-align: center;
}

.th-preview, .td-preview {
    width: 80px;
    text-align: center;
}

.th-info, .td-info {
    /* 自动填充剩余空间 */
}

.th-actions, .td-actions {
    width: 60px;
    text-align: center;
}

.td-checkbox {
    width: 40px;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0;
}

/* 让所有的复选框居中 */
:deep(.van-checkbox) {
    margin: 0 auto;
    display: flex;
    justify-content: center;
    align-items: center;
}

:deep(.van-checkbox__icon) {
    margin: 0 auto;
}

:deep(.van-checkbox__label) {
    display: none;
}

.image-preview-cell {
    width: 60px;
    height: 60px;
    overflow: hidden;
    border-radius: 4px;
    border: 1px solid #eee;
    margin: auto;
}

.image-preview-cell img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    cursor: pointer;
}

.td-info {
    line-height: 1.5;
}

.file-name {
    font-size: 14px;
    color: #303133;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    display: block;
    margin-bottom: 4px;
}

.file-meta {
    display: flex;
    gap: 10px;
    align-items: center;
}

.file-size,
.upload-time {
    font-size: 12px;
    color: #909399;
}

.action-icon {
    color: #909399;
    cursor: pointer;
    font-size: 18px;
    transition: color 0.2s ease;
}

.action-icon:hover {
    color: #f56c6c;
}

.page-size-control {
    display: flex;
    flex-direction: column;
    gap: 4px;
    min-width: 120px;
}

.quick-options {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}

.quick-options span {
    padding: 2px 6px;
    border-radius: 4px;
    font-size: 12px;
    color: #666;
    cursor: pointer;
    background: #f7f8fa;
    border: 1px solid #ebedf0;
}

.quick-options span:hover {
    color: #1989fa;
    border-color: #1989fa;
}

.quick-options span.active {
    color: #fff;
    background: #1989fa;
    border-color: #1989fa;
}

/* 仅在PC端隐藏操作列的时间显示 */
@media (min-width: 769px) {
    /* PC端显示文件信息内的元数据，隐藏操作列的时间 */
    .file-meta {
        display: flex;
        flex-direction: column;
        gap: 2px;
        text-align: left;
        align-items: flex-start;
        margin-bottom: 6px;
    }
    
    .file-size {
        font-size: 12px;
        color: #ff9800;
        font-weight: 500;
        text-align: left;
    }
    
    .upload-time {
        font-size: 12px;
        color: #909399;
        text-align: left;
    }
    
    /* 确保PC端文件信息区整体左对齐 */
    .td-info {
        text-align: left;
    }
    
    .td-actions .time-display {
        display: none;
    }
    
    .mobile-file-size {
        display: none;
    }
}

/* 移动端样式调整 */
@media (max-width: 768px) {
    .gallery-list {
        padding: 12px;
    }

    .list-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;
        margin-bottom: 12px;
    }

    .list-header h3 {
        font-size: 16px;
        margin: 0;
        width: 100%;
    }

    .header-actions {
        width: 100%;
        flex-wrap: wrap;
        gap: 8px;
    }

    .page-size-control {
        width: 100%;
        margin-bottom: 8px;
    }

    .quick-options {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 8px;
        margin-top: 8px;
    }

    .quick-options span {
        text-align: center;
        padding: 6px 0;
        font-size: 13px;
    }

    :deep(.van-field) {
        background-color: #f0f2f5;
        padding: 8px 16px;
    }

    :deep(.van-field__control) {
        background-color: #f0f2f5;
        font-size: 14px;
    }

    .header-actions .van-button {
        flex: 1;
        min-width: 80px;
    }

    .gallery-table {
        display: block;
        margin-top: 0;
    }

    .gallery-table thead {
        display: none;
    }

    .gallery-table tbody {
        display: block;
    }

    .gallery-table tr.gallery-row {
        position: relative;
        display: flex;
        flex-wrap: wrap;
        padding: 12px 12px 8px;
        margin-bottom: 12px;
        background: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        border: 1px solid #eee;
    }

    .gallery-table td {
        border: none;
        padding: 0;
    }

    .td-checkbox {
        width: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 8px;
        position: relative;
    }
    
    /* 确保移动端的复选框也是正确居中的 */
    .td-checkbox :deep(.van-checkbox) {
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        margin: 0;
    }
    
    .td-serial {
        display: none; /* 在移动端隐藏序号 */
    }

    .td-preview {
        width: 70px;
        margin-right: 12px;
    }

    .image-preview-cell {
        width: 70px;
        height: 70px;
        margin: 0;
        border-radius: 6px;
    }

    .td-info {
        flex: 1;
        min-width: 0;
        display: flex;
        flex-direction: column;
        justify-content: center;
    }

    .td-info .file-name {
        font-size: 14px;
        font-weight: 500;
        margin-bottom: 4px;
        color: #333;
    }

    .td-info .file-meta {
        display: none; /* 在移动端隐藏PC端风格的元信息 */
    }
    
    /* 移动端文件大小 */
    .td-info .mobile-file-size {
        font-size: 12px;
        color: #666;
        display: flex;
        align-items: center;
        margin-bottom: 6px;
    }
    
    /* 添加底部时间区域 */
    .td-actions {
        width: 100%;
        display: flex;
        justify-content: space-between; /* 两端对齐 */
        margin-top: 8px;
        padding: 8px 4px 4px;
        border-top: 1px solid #f0f0f0;
        background-color: transparent;
    }
    
    /* 创建时间显示区域 */
    .time-display {
        font-size: 12px;
        color: #666;
        display: flex;
        flex-direction: column;
        gap: 6px;
        padding-left: 5px;
        justify-content: center;
    }
    
    .size-info, .time-info {
        display: flex;
        align-items: center;
    }
    
    .size-icon, .time-icon {
        margin-right: 4px;
        font-size: 14px;
    }
    
    .size-icon {
        color: #ff9800;
    }
    
    .time-icon {
        color: #1989fa;
    }

    /* 调整分页器样式 */
    .pagination-wrapper {
        flex-direction: column;
        gap: 12px;
    }

    .pagination-info {
        font-size: 12px;
    }

    /* 确保复选框在移动端正确显示 */
    :deep(.van-checkbox) {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100%;
    }

    :deep(.van-checkbox__label) {
        display: none;
    }

    /* 移动端的操作图标样式 */
    .action-icon {
        font-size: 16px;
        padding: 4px 8px;
    }

    /* 在移动端隐藏PC端元信息 */
    .pc-file-meta {
        display: none;
    }
}

:deep(.van-field) {
    background-color: #f5f7fa;
}

:deep(.van-field__control) {
    background-color: #f5f7fa;
}

.pc-file-meta {
    display: flex;
    flex-direction: column;
    gap: 2px;
    margin-top: 4px;
}

.pc-file-size {
    font-size: 12px;
    color: #ff9800;
    font-weight: 500;
}

.pc-upload-time {
    font-size: 12px;
    color: #909399;
}
</style> 